<template>
  <div class="order-page" v-if="orderInfo">
    <!-- 顶部导航 -->
    <div class="nav-header">
      <button class="back-button" @click="goBack">
        <svg
          xmlns="http://www.w3.org/2000/svg"
          width="24"
          height="24"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          stroke-width="2"
          stroke-linecap="round"
          stroke-linejoin="round"
        >
          <path d="m15 18-6-6 6-6" />
        </svg>
      </button>
      <h2>确认订单</h2>
    </div>

    <!-- 收货地址 -->
    <div class="address-section">
      <AddressSelector :address="address" @click="selectAddress" />
    </div>

    <!-- 商品信息 -->
    <div class="product-section">
      <div class="section-title">商品信息 ({{ orderInfo.totalCount }}件)</div>
      <div class="product-card" v-for="(item, index) in orderInfo.items" :key="index">
        <img :src="item.imageUrl" :alt="item.name" class="product-image">
        <div class="product-info">
          <div class="product-name">{{ item.name }}</div>
          <div class="product-quantity">x{{ item.quantity }}</div>
          <div class="product-price">
            <span class="price-label">¥</span>
            <span class="price-value">{{ item.price }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 订单信息 -->
    <div class="order-info-section">
      <div class="info-item">
        <span class="label">商品总数</span>
        <span class="value">{{ orderInfo.totalCount }}件</span>
      </div>
      <div class="info-item">
        <span class="label">商品总价</span>
        <span class="value">¥{{ orderInfo.totalPrice }}</span>
      </div>
      <div class="info-item total">
        <span class="label">实付金额</span>
        <span class="value">¥{{ orderInfo.totalPrice - orderInfo.discount }}</span>
      </div>
    </div>

    <!-- 支付方式 -->
    <div class="payment-section">
      <div class="section-title">支付方式</div>
      <div class="payment-options">
        <div
          v-for="method in paymentMethods"
          :key="method.id"
          class="payment-option"
          :class="{ active: selectedPayment === method.id }"
          @click="selectedPayment = method.id"
        >
          <div class="payment-icon">
            <img :src="method.icon" :alt="method.name">
          </div>
          <div class="payment-name">{{ method.name }}</div>
          <div class="payment-check" v-if="selectedPayment === method.id">
            <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
              <path d="M20 6L9 17l-5-5"/>
            </svg>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部结算栏 -->
    <div class="checkout-bar">
      <div class="price-info">
        <span>实付金额：</span>
        <span class="total-price">¥{{ orderInfo.totalPrice - orderInfo.discount }}</span>
      </div>
      <button class="submit-button" @click="submitOrder">提交订单</button>
    </div>

    <!-- 支付确认弹窗 -->
    <div class="payment-dialog" v-if="showPaymentDialog">
      <div class="dialog-content">
        <div class="dialog-header">
          <h3>{{
            paymentStatus === 'success' ? '支付成功' :
            paymentStatus === 'loading' ? '支付处理中' :
            '确认支付'
          }}</h3>
          <button class="close-button" @click="closePaymentDialog" v-if="paymentStatus === 'pending'">×</button>
        </div>
        <div class="dialog-body">
          <template v-if="paymentStatus === 'success'">
            <div class="success-icon">
              <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="#8B5CF6" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"></path>
                <polyline points="22 4 12 14.01 9 11.01"></polyline>
              </svg>
            </div>
            <div class="success-message">
              <h4>订单支付成功</h4>
              <p>感谢您的购买！</p>
            </div>
          </template>
          <template v-else-if="paymentStatus === 'loading'">
            <div class="loading-container">
              <div class="loading-spinner"></div>
              <p class="loading-text">正在处理支付，请稍候...</p>
            </div>
          </template>
          <template v-else>
            <div class="payment-amount">
              <span>支付金额：</span>
              <span class="amount">¥{{ orderInfo.totalPrice - orderInfo.discount }}</span>
            </div>
            <div class="payment-method">
              <span>支付方式：</span>
              <span>{{ getPaymentMethodName(selectedPayment) }}</span>
            </div>
          </template>
        </div>
        <div class="dialog-footer">
          <template v-if="paymentStatus === 'success'">
            <button class="confirm-button" @click="goToOrderList">查看订单</button>
          </template>
          <template v-else-if="paymentStatus === 'loading'">
            <button class="confirm-button" disabled>处理中...</button>
          </template>
          <template v-else>
            <button class="cancel-button" @click="closePaymentDialog">取消</button>
            <button class="confirm-button" @click="confirmPayment">确认支付</button>
          </template>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import AddressSelector from '@/components/AddressSelector/AddressSelector.vue'
import{getAddressList}from '@/views/address/api/index'
import{createMultiOrder}from '@/views/order/api/index'
import { payOrder } from '../api/index'
import { useUserStore } from '@/stores/user'
const userStore = useUserStore()
const userId = userStore.userInfo.id
defineOptions({
  name: 'CartOrder'
})
const router = useRouter()
const route = useRoute()
const orderInfo = ref(null)
const selectedPayment = ref('alipay')
const showPaymentDialog = ref(false)
const paymentQRCode = ref('')
const paymentStatus = ref('pending') // 'pending' | 'loading' | 'success'

// 支付方式
const paymentMethods = [
  {
    id: 'alipay',
    name: '支付宝',
    icon: 'https://felixai.oss-cn-chengdu.aliyuncs.com/8888.png'
  },
  {
    id: 'wechat',
    name: '微信支付',
    icon: 'https://felixai.oss-cn-chengdu.aliyuncs.com/7777.png'
  },
]

const goBack = () => {
  router.go(-1)
}

// 地址数据
const address = ref({
  name: '未填写收货人',
  phone: '未填写电话',
  fullAddress: '未填写地址'
})
// 监听路由参数变化
onMounted(async() => {
  // 从路由参数中获取订单信息
  const orderInfoParam = route.query.orderInfo
  const res3 = await getAddressList()
  address.value.id = res3.data.data[0].addressesId
  address.value.name = res3.data.data[0].recipientName
  address.value.phone = res3.data.data[0].phone
  address.value.fullAddress = res3.data.data[0].address
  // address.value = res3.data.data[0]
  if (orderInfoParam) {
    try {
      orderInfo.value = JSON.parse(orderInfoParam)
      console.log('接收到的订单信息:', orderInfo.value)
    } catch (error) {
      console.error('解析订单信息失败:', error)
    }
  }

  // 获取选中的地址信息
  const selectedAddress = route.query.selectedAddress
  if (selectedAddress) {
    try {
      address.value = JSON.parse(selectedAddress)
    } catch (error) {
      console.error('解析地址信息失败:', error)
    }
  }
})

const selectAddress = () => {
  // 跳转到地址选择页面时携带订单信息
  router.push({
    path: '/address',
    query: {
      orderInfo: JSON.stringify(orderInfo.value),
      from: 'cart'
    }
  })
}

const getPaymentMethodName = (methodId) => {
  const method = paymentMethods.find(m => m.id === methodId)
  return method ? method.name : ''
}

const goToOrderList = () => {
 router.push(`/order/myOrders/${userId}`)

  closePaymentDialog()

}

const closePaymentDialog = () => {
  showPaymentDialog.value = false
  paymentQRCode.value = ''
  paymentStatus.value = 'pending'
}

const confirmPayment = () => {
  // 显示加载动画
  console.log(dataOrderId.value)
  paymentStatus.value = 'loading'

  // 模拟支付过程
  setTimeout(() => {
    paymentStatus.value = 'success'
    dataOrderId.value.forEach(async order => {
       await payOrder(order.orderNumber)

    })
  }, 2000) // 2秒的加载动画
}
const dataOrderId = ref([])
const submitOrder = async() => {
  const orderDataToSubmit = orderInfo.value.items.map(item => ({
    addressesId: address.value.id,
    productId: item.productId,
    productName: item.name,
    quantity: item.quantity,
    productPrice: item.price,
    productImageUrl: item.imageUrl,
    recipientName: address.value.name,
    phone: address.value.phone,
    address: address.value.fullAddress,
  }))

  const test2 = orderDataToSubmit
  console.log('提交订单数据:', test2)
  const res = await createMultiOrder(test2)

  if(res.data.code === 200){
    dataOrderId.value = res.data.data
    showPaymentDialog.value = true
  }
}
</script>

<style lang="scss" scoped>
.order-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 60px;
}

.nav-header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 44px;
  background-color: white;
  display: flex;
  align-items: center;
  padding: 0 16px;
  z-index: 100;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);

  .back-button {
    background: none;
    border: none;
    padding: 8px;
    margin-left: -8px;
    cursor: pointer;
  }

  h2 {
    flex: 1;
    text-align: center;
    margin: 0;
    font-size: 16px;
  }
}

.section-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 12px;
}

.address-section {
  margin-top: 44px;
  background-color: white;
  padding: 16px;
  margin-bottom: 12px;
}

.product-section {
  background-color: white;
  padding: 16px;
  margin-bottom: 12px;

  .product-card {
    display: flex;
    align-items: center;
    padding: 12px 0;
    border-bottom: 1px solid #f0f0f0;

    &:last-child {
      border-bottom: none;
    }

    .product-image {
      width: 70px;
      height: 70px;
      object-fit: cover;
      border-radius: 8px;
      margin-right: 12px;
      border: 1px solid #f0f0f0;
    }

    .product-info {
      flex: 1;
      position: relative;

      .product-name {
        font-size: 14px;
        margin-bottom: 4px;
        line-height: 1.4;
        max-height: 40px;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-box-orient: vertical;
      }

      .product-quantity {
        font-size: 12px;
        color: #999;
        margin-bottom: 4px;
      }

      .product-price {
        color: #ff3b30;

        .price-label {
          font-size: 12px;
        }

        .price-value {
          font-size: 16px;
          font-weight: bold;
        }
      }
    }
  }
}

.order-info-section {
  background-color: white;
  padding: 16px;
  margin-bottom: 12px;

  .info-item {
    display: flex;
    justify-content: space-between;
    margin-bottom: 12px;

    &:last-child {
      margin-bottom: 0;
    }

    .label {
      color: #666;
    }

    .value {
      color: #333;
    }

    &.total {
      margin-top: 8px;
      padding-top: 8px;
      border-top: 1px solid #f0f0f0;

      .label, .value {
        font-weight: bold;
      }

      .value {
        color: #ff3b30;
      }
    }
  }
}

.payment-section {
  background-color: white;
  padding: 16px;

  .payment-options {
    .payment-option {
      display: flex;
      align-items: center;
      padding: 12px 0;
      border-bottom: 1px solid #f0f0f0;
      cursor: pointer;

      &:last-child {
        border-bottom: none;
      }

      &.active {
        .payment-name {
          color: #8B5CF6;
        }
      }

      .payment-icon {
        width: 24px;
        height: 24px;
        margin-right: 12px;

        img {
          width: 100%;
          height: 100%;
          object-fit: contain;
        }
      }

      .payment-name {
        flex: 1;
        font-size: 14px;
      }

      .payment-check {
        color: #8B5CF6;
      }
    }
  }
}

.checkout-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 50px;
  background-color: white;
  display: flex;
  align-items: center;
  padding: 0 16px;
  box-shadow: 0 -1px 3px rgba(0, 0, 0, 0.05);

  .price-info {
    flex: 1;

    .total-price {
      color: #ff3b30;
      font-size: 18px;
      font-weight: bold;
    }
  }

  .submit-button {
    width: 120px;
    height: 36px;
    background-color: #8B5CF6;
    color: white;
    border: none;
    border-radius: 18px;
    font-size: 16px;
    margin-left: 16px;
    cursor: pointer;

    &:active {
      opacity: 0.9;
    }
  }
}

.payment-dialog {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;

  .dialog-content {
    background-color: white;
    border-radius: 12px;
    width: 90%;
    max-width: 320px;
    padding: 20px;
  }

  .dialog-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h3 {
      margin: 0;
      font-size: 18px;
    }

    .close-button {
      background: none;
      border: none;
      font-size: 24px;
      color: #999;
      cursor: pointer;
      padding: 0;
    }
  }

  .dialog-body {
    .payment-amount {
      margin-bottom: 16px;
      font-size: 16px;

      .amount {
        color: #ff3b30;
        font-weight: bold;
        font-size: 20px;
      }
    }

    .payment-method {
      margin-bottom: 20px;
      color: #666;
    }

    .payment-qr {
      text-align: center;
      margin-bottom: 20px;

      img {
        width: 200px;
        height: 200px;
        margin-bottom: 12px;
      }

      p {
        color: #666;
        font-size: 14px;
        margin: 0;
      }
    }

    .success-icon {
      text-align: center;
      margin-bottom: 20px;
    }

    .success-message {
      text-align: center;
      margin-bottom: 20px;

      h4 {
        color: #333;
        font-size: 18px;
        margin: 0 0 8px 0;
      }

      p {
        color: #666;
        font-size: 14px;
        margin: 0;
      }
    }

    .loading-container {
     height: 100px;
      text-align: center;
      padding: 20px 0;

      .loading-spinner {
        width: 40px;
        height: 40px;
        margin: 0 auto 16px;
        border: 3px solid #f3f3f3;
        border-top: 3px solid #8B5CF6;
        border-radius: 50%;
        animation: spin 1s linear infinite;
      }

      .loading-text {
        color: #666;
        font-size: 14px;
        margin: 0;
      }
    }
  }

  .dialog-footer {
    display: flex;
    gap: 12px;

    button {
      flex: 1;
      height: 40px;
      border-radius: 20px;
      font-size: 16px;
      cursor: pointer;

      &:disabled {
        opacity: 0.7;
        cursor: not-allowed;
      }
    }

    .cancel-button {
      background-color: #f5f5f5;
      border: none;
      color: #666;
    }

    .confirm-button {
      background-color: #8B5CF6;
      border: none;
      color: white;
    }
  }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style>
